<?php
use Workerman\Lib\Timer;
use \GatewayWorker\Lib\Gateway;

class Events {

    public static function onWorkerStart($client_id){

    }

    public static function onConnect($client_id){
    }

    public static function onMessage($client_id, $message) {
        $message_data = json_decode($message, true);

        if(!$message_data){
            return ;
        }
        
        switch($message_data['type']) {

            case 'pong':
                if(!isset($_SESSION['room_id'])) {
                    return;
                }
                $room_info = $_SESSION['room_info'];
                // [0] teacher [1] student [2] time
                $teacher_student_time = explode( ':', $room_info);

                $count_time = $teacher_student_time[3] - time();
                $count_time = $count_time >= 0 ? $count_time : 0;
                echo PHP_EOL;
                echo PHP_EOL;
                echo "-----------pong timer-----------";
                echo PHP_EOL;
                echo 'teacher_id:',$teacher_student_time[0].PHP_EOL;
                echo "user_id:{$_SESSION['user_id']}------";
                echo secToTime($count_time);
                echo '------------';
                if(time() >= $teacher_student_time[3]){
                    Gateway::sendToGroup($_SESSION['room_id'] ,json_encode([
                        'type' => 'logout',
                        'user_id' => $_SESSION['user_id'],
                        'icon' => $_SESSION['user_icon'],
                        'content' => "时间到了",
                        'time' => time(),
                        'count_time' => $count_time
                    ]));
                    Gateway::closeClient($client_id);
                }
		return ;
                
            case 'login':
                // 判断是否有房间号
                if(!isset($message_data['room_id'])) {
                    throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
                }
                $room_info = base64_decode($message_data['room_id']);
                // [0] teacher [1] student [2] time
                $teacher_student_time = explode( ':', $room_info);
                $room_id = (int) $teacher_student_time[0].$teacher_student_time[1];

                $count_time = $teacher_student_time[3] - time();
                $count_time = $count_time >= 0 ? $count_time : 0;


                if(time() <= $teacher_student_time[2]){
                    return ;
                }
                if($teacher_student_time[3] <= time()){
                    Gateway::sendToGroup($_SESSION['room_id'] ,json_encode([
                        'type' => 'logout',
                        'user_id' => $message_data['user_id'],
                        'icon' => $message_data['icon'],
                        'content' => "时间到了",
                        'time' => time(),
                        'count_time' => $count_time
                    ]));
                    Gateway::closeClient($client_id);
                }

                if($message_data['user_type']=='teacher'&&$teacher_student_time[0] == $message_data['user_id']){
                    $content = "您的咨询师已进入！";
                }else if($message_data['user_type']=='student'&&$teacher_student_time[1] == $message_data['user_id']){
                    $content = "Hi!~";
                }else{
                    Gateway::closeClient($client_id);
                }

                $_SESSION['room_id'] = $room_id;
                $_SESSION['room_info'] = $room_info;
                $_SESSION['user_id'] = $message_data['user_id'];
		        $_SESSION['user_icon']=$message_data['icon'];
              
                $new_message = array(
                    'type'=>'say', 
                    'user_id'=>$message_data['user_id'],
                    'icon'=>$message_data['icon'],
                    'content'=>$content,
                    'count_time'=>$count_time
                );
                Gateway::sendToGroup($_SESSION['room_id'], json_encode($new_message));
                Gateway::joinGroup($client_id, $_SESSION['room_id']);
                return;
                
            case 'say'||'audio':
                // 非法请求
                if(!isset($_SESSION['room_id'])) {
                    throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}");
                }
                
                $room_info = $_SESSION['room_info'];
                // [0] teacher [1] student [2] time
                $teacher_student_time = explode( ':', $room_info);

                $count_time = $teacher_student_time[3] - time();
                $count_time = $count_time >= 0 ? $count_time : 0;
                

                if(time() <= $teacher_student_time[2]){
                    return ;
                }

                if(time() >= $teacher_student_time[3]){
                    Gateway::sendToGroup($_SESSION['room_id'] ,json_encode([
                        'type' => 'logout',
                        'user_id' => $message_data['user_id'],
                        'icon' => $message_data['icon'],
                        'content' => "时间到了",
                        'time' => time(),
                        'count_time' => $count_time
                    ]));
                    Gateway::closeClient($client_id);
                }

                if($message_data['user_type']=='teacher'&&$teacher_student_time[0] == $message_data['user_id']){
                }else if($message_data['user_type']=='student'&&$teacher_student_time[1] == $message_data['user_id']){
                }else{
                    Gateway::closeClient($client_id);
                }

                $new_message = array(
                    'type'=>$message_data['type'], 
                    'user_id'=>$message_data['user_id'],
                    'icon'=>$message_data['icon'],
                    'content'=>$message_data['type']=='audio'?$message_data['content']:nl2br(htmlspecialchars($message_data['content'])),
                    'count_time'=>$count_time
                );
                return Gateway::sendToGroup($_SESSION['room_id'] ,json_encode($new_message));
        }
   }
   
   /**
    * 当客户端断开连接时
    * @param integer $client_id 客户端id
    */
   public static function onClose($client_id)
   {
       if(isset($_SESSION['room_id']))
       {
           $room_id = $_SESSION['room_id'];
           $room_info = $_SESSION['room_info'];
           // [0] teacher [1] student [2] time
           $teacher_student_time = explode( ':', $room_info);
           $count_time = $teacher_student_time[3] - time();
           $count_time = $count_time >= 0 ? $count_time : 0;
            echo PHP_EOL;
            echo PHP_EOL;
            echo "-----------logout timer-----------";
            echo PHP_EOL;
            echo "user_id:{$_SESSION['user_id']}------";
            echo secToTime($count_time);
           Gateway::closeClient($client_id);
           Gateway::sendToGroup($_SESSION['room_id'] ,json_encode([
            'type'=>'logout',
            'user_id'=>$_SESSION['user_id'],
            'icon'=>$_SESSION['user_icon'],
            'content'=>'对方已退出',
            'count_time'=>$count_time
           ]));
       }
   }
  
}
function secToTime($times){  
$result = '00:00:00';  
if ($times>0) {  
$hour = floor($times/3600);  
$minute = floor(($times-3600 * $hour)/60);  
$second = floor((($times-3600 * $hour) - 60 * $minute) % 60);  
$result = $hour.':'.$minute.':'.$second;  
                                                                                                }  
return $result;  
}  

